<?php

namespace App\Console\Commands;

use App\Events\LoanRequestRetryEvent;
use App\Facades\SamLogFacade;
use App\Models\LoanRequestFailedLog;
use App\Models\User;
use App\Models\UserApplyRiskLog;
use App\Models\UserBankCard;
use App\Models\UserInfo;
use App\Models\UserLoanRequest;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class FailedUserSync extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:failed {action : sync|solve|retry|retryRisk}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Failed user';

    /**
     * The console command action. month|common|money|help
     *
     * @var string
     */
    protected $action;

    /**
     * Description: 用户信息同步失败用户重新同步
     * Author: Gxs
     */
    public function sync()
    {
        $len = Redis::llen('syncFail');
        if($len>0){
            SamLogFacade::debug($len."个需要同步信息的用户");
            while($len>0){
                $list = Redis::rPop('syncFail');
                $info = json_decode($list,true);
                User::userSync($info['user_id'],$info['bank_card_id'],$info['user_info_id'],$info['amount']);
                $len--;
            }
        }
        $this->info('sync api done');
    }

    /**
     * Description: 用户信息同步失败用户重新同步
     * Author: cg
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function solve()
    {
        $faildUsers = UserLoanRequest::from('user_loan_requests as a')
            ->select(['a.id as loan_id', 'b.id as user_id', 'b.nfsp_user_id', 'c.limit','a.cash_card_choice_id', 'a.user_base_info_id'])
            ->leftJoin('users as b','a.user_id', '=', 'b.id')
            ->leftJoin('user_apply_risk_logs as c','a.id', '=', 'c.loan_request_id')
            ->where('a.status', UserLoanRequest::STATUS_WAIT_FOR_RISK)
            ->where('a.current', UserLoanRequest::CURRENT_NOW)
            ->where('a.risk_status', UserLoanRequest::STATUS_UN_APPLY)
            ->whereBetween('a.created_at', [Carbon::parse(date("Y-m-d H:i:s"))->addDay(-10), Carbon::parse(date("Y-m-d H:i:s"))])
            ->whereNull('b.nfsp_user_id')
            ->get();
        foreach ($faildUsers as $faildUserLoan){
            $bank_card_id = $faildUserLoan->cash_card_choice_id;
            $user_info_id = $faildUserLoan->user_base_info_id;
            $result = User::userSync($faildUserLoan->user_id, $bank_card_id, $user_info_id, $faildUserLoan->limit);
            Log::debug("userSync solve user:".$faildUserLoan->user_id."-".$bank_card_id."-".$user_info_id."-".$faildUserLoan->limit/100);
            Log::debug("userSync solve result:".json_encode($result, JSON_UNESCAPED_UNICODE));
        }
    }


    public function retryRisk(){
        $loan_ids = LoanRequestFailedLog::whereIn('message' , ['参数授权文件不能为空','签名验证失败'])->pluck('nfsp_user_id');
        $ret = UserLoanRequest::from('user_loan_requests as a')
            ->select(['a.id as loan_id', 'b.id as user_id', 'b.nfsp_user_id', 'a.cash_card_choice_id', 'a.user_base_info_id'])
            ->leftJoin('users as b','a.user_id', '=', 'b.id')
            ->whereIn('b.nfsp_user_id', $loan_ids)
            ->where('a.current', UserLoanRequest::CURRENT_NOW)
            ->where('a.risk_status',UserLoanRequest::STATUS_UN_APPLY)
            ->where('a.status', UserLoanRequest::STATUS_LACK_INFO)
            ->get();
        foreach ($ret as $value){
            $risks = UserApplyRiskLog::where('loan_request_id', $value->loan_id)->first();
            if($risks){
                $bank_card_id = $value->cash_card_choice_id;
                $user_info_id = $value->user_base_info_id;
                echo '用户id：'.$value->user_id . "|userSync\n";
                $result = User::userSync($value->user_id, $bank_card_id, $user_info_id, $risks->limit);
                usleep(500000);
                SamLogFacade::debug("test-retry-risk--------".json_encode($result, JSON_UNESCAPED_UNICODE));
            }
        }

    }

    public function retry(){
//        $loans = UserLoanRequest::where('status', 10)->where('current', 1)
//            ->where('risk_status', 1)
//            ->where('updated_at', '>=','2019-03-26 15:00:00')->where('updated_at','<=','2019-03-26 22:00:00')
//            ->pluck('user_id');
        $loans = UserLoanRequest::where('status', 10)->where('current', 1)
            ->where('risk_status', 1)
            ->where('updated_at', '>=','2019-03-26 15:00:00')->where('updated_at','<=','2019-03-26 22:00:00')
            ->pluck('id');
//        $users = User::whereIn('id', $loans)->whereNotNull('nfsp_user_id')->get();
//        dd($users->count());
        $logs = LoanRequestFailedLog::select([
            DB::raw('count(loan_request_id) as num'),
            'message',
            DB::raw('group_concat(loan_request_id) as ids')
        ])->whereIn('loan_request_id', $loans)->groupBy('message')->get();
//        dd($logs->toArray());
        foreach ($logs as $log){
            $ids_arr = explode(',', $log->ids);
            $uids = UserLoanRequest::whereIn('id', $ids_arr)->pluck('user_id')->toArray();
            $nfsp_user_ids = User::whereIn('id', $uids)->pluck('nfsp_user_id')->toArray();
            dump($nfsp_user_ids);
        }

//        dd($logs->toArray());
//        $loan_id = LoanRequestFailedLog::where('message', '签名验证失败')->pluck('loan_request_id');
//        $loans = UserLoanRequest::whereIn('id', $loan_id);
//        foreach ($loans as $loan){
//            event(new LoanRequestRetryEvent($loan));
//        }
    }


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->initAction();
        $this->runAction();
    }

    /**
     * Description: Initialize command action.
     * Author: Gxs
     */
    protected function initAction()
    {
        $this->action = $this->argument('action');

        if (!in_array($this->action, ['sync', 'solve', 'retry', 'retryRisk'])) {
            $this->error("Invalid argument '{$this->action}'. Expected 'sync'.");
            exit(1);
        }
    }

    /**
     * Description: Run action.
     * Author: Gxs
     */
    protected function runAction()
    {
        $this->{$this->action}();
    }
}
